<template>
  <div class="chat-container">
    <div class="inheritor-info">
      <el-avatar :size="60" :src="inheritor.avatar || defaultAvatar" />
      <div class="info">
        <h3>{{ inheritor.name }}</h3>
        <div class="meta">
          <el-tag :type="isOnline ? 'success' : 'info'" size="small" effect="dark">
            {{ isOnline ? '在线' : '离线' }}
          </el-tag>
          <span class="category">{{ inheritor.category || '传统技艺' }}</span>
        </div>
      </div>
    </div>

    <!-- 消息容器 -->
    <div class="messages-wrapper" ref="messagesContainer">
      <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message-bubble', message.senderType === 'user' ? 'user' : 'inheritor']"
      >
        <el-avatar
            v-if="message.senderType === 'inheritor'"
            :src="inheritor.avatar || defaultAvatar"
            class="avatar"
        />
        <div class="content-wrapper">
          <div class="meta">
            <span class="sender">{{ message.senderType === 'user' ? '我' : inheritor.name }}</span>
            <span class="time">{{ formatTime(message.timestamp) }}</span>
          </div>
          <div class="content">
            <div v-if="message.type === 'text'" class="text">
              {{ message.content }}
            </div>
            <img
                v-else-if="message.type === 'image'"
                :src="message.content"
                class="image-message"
                @click="previewImage(message.content)"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-wrapper">
        <el-input
            v-model="inputContent"
            type="textarea"
            :rows="2"
            placeholder="输入消息..."
            @keyup.enter.exact="sendMessage"
            resize="none"
        />
        <div class="action-buttons">
          <el-button type="primary" @click="sendMessage" :disabled="!inputContent.trim()">
            发送
          </el-button>
          <el-upload
              action="#"
              :show-file-list="false"
              :before-upload="handleImageUpload"
          >
            <el-button type="info" icon="el-icon-picture" />
          </el-upload>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// 模拟API
const chatMock = {
  getHistory: (inheritorId) => [
    {
      id: 1,
      senderType: 'inheritor',
      type: 'text',
      content: '您好！我是非遗传承人，有什么可以帮您？',
      timestamp: Date.now() - 3600000
    },
    {
      id: 2,
      senderType: 'user',
      type: 'text',
      content: '我想了解传统技艺的传承情况',
      timestamp: Date.now() - 1800000
    }
  ],

  sendMessage: (payload) => {
    const replies = {
      text: [
        `关于"${payload.content}"，这项技艺的关键在于...`,
        '这个问题很好，我们的传统做法是...',
        '感谢关注，具体来说...',
        '我正在整理资料，稍后详细解答'
      ],
      image: [
        '这张图片展示了传统工艺的关键步骤',
        '感谢分享图片，这里可以看到...',
        '图片中的工具是传统制作的核心器具'
      ]
    }

    return {
      id: Date.now(),
      senderType: 'inheritor',
      type: payload.type,
      content: payload.type === 'text'
          ? replies.text[Math.floor(Math.random() * replies.text.length)]
          : 'https://dummyimage.com/200x150/4CAF50/fff&text=示例回复图片',
      timestamp: Date.now()
    }
  }
}

export default {
  props: {
    inheritor: {
      type: Object,
      default: () => ({
        id: 'default-1',
        name: '非遗传承人',
        avatar: '',
        category: '传统技艺'
      })
    }
  },
  setup(props) {
    const defaultAvatar = ref('https://dummyimage.com/60x60/4CAF50/fff&text=非遗')
    const messagesContainer = ref(null)
    const inputContent = ref('')
    const isOnline = ref(true)
    const messages = ref(chatMock.getHistory(props.inheritor.id))

    // 格式化时间
    const formatTime = (timestamp) => {
      const date = new Date(timestamp)
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }

    // 发送消息
    const sendMessage = async () => {
      if (!inputContent.value.trim()) return

      try {
        // 添加用户消息
        const userMsg = {
          id: Date.now(),
          senderType: 'user',
          type: 'text',
          content: inputContent.value.trim(),
          timestamp: Date.now()
        }
        messages.value.push(userMsg)
        inputContent.value = ''
        scrollToBottom()

        // 模拟回复
        setTimeout(() => {
          const response = chatMock.sendMessage({
            inheritorId: props.inheritor.id,
            type: 'text',
            content: userMsg.content
          })
          messages.value.push(response)
          scrollToBottom()
        }, 1000)

      } catch (error) {
        ElMessage.error('发送失败')
      }
    }

    // 处理图片上传
    const handleImageUpload = (file) => {
      if (!file.type.startsWith('image/')) {
        ElMessage.error('请上传图片文件')
        return false
      }

      const reader = new FileReader()
      reader.onload = (e) => {
        // 添加用户图片消息
        const userMsg = {
          id: Date.now(),
          senderType: 'user',
          type: 'image',
          content: e.target.result,
          timestamp: Date.now()
        }
        messages.value.push(userMsg)
        scrollToBottom()

        // 模拟回复
        setTimeout(() => {
          const response = chatMock.sendMessage({
            inheritorId: props.inheritor.id,
            type: 'image',
            content: userMsg.content
          })
          messages.value.push(response)
          scrollToBottom()
        }, 1000)
      }
      reader.readAsDataURL(file)

      return false
    }

    // 图片预览
    const previewImage = (src) => {
      window.open(src, '_blank')
    }

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      })
    }

    // 初始化
    onMounted(() => {
      scrollToBottom()
      setInterval(() => {
        isOnline.value = Math.random() > 0.3
      }, 5000)
    })

    return {
      defaultAvatar,
      messagesContainer,
      inputContent,
      isOnline,
      messages,
      formatTime,
      sendMessage,
      handleImageUpload,
      previewImage
    }
  }
}
</script>


<!-- 保持之前提供的样式不变 -->

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 70vh;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.inheritor-info {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.inheritor-info .info {
  margin-left: 12px;
}

.inheritor-info h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.meta {
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.messages-wrapper {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #fafafa;
}

.message-bubble {
  display: flex;
  margin-bottom: 16px;
  gap: 12px;
}

.message-bubble.user {
  flex-direction: row-reverse;
}

.avatar {
  flex-shrink: 0;
}

.content-wrapper {
  max-width: 70%;
}

.meta {
  margin-bottom: 4px;
  font-size: 12px;
  color: #909399;
}

.sender {
  margin-right: 8px;
  font-weight: 500;
}

.content {
  position: relative;
  word-wrap: break-word;
}

.text {
  padding: 12px 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.user .text {
  background: #409eff;
  color: white;
}

.image-message {
  max-width: 300px;
  max-height: 200px;
  border-radius: 4px;
  cursor: zoom-in;
  transition: transform 0.2s;
}

.image-message:hover {
  transform: scale(1.02);
}

.input-area {
  border-top: 1px solid #ebeef5;
  padding: 16px;
}

.input-wrapper {
  display: flex;
  gap: 12px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 4px;
}
</style>